package com.example.viewpagerdemo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.example.viewpagerdemo.databinding.ActivityMainBinding
import com.example.viewpagerdemo.databinding.FragmentRotateBinding
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val viewPager2 = findViewById<ViewPager2>(R.id.viewPager2)
        val tabLayout = findViewById<TabLayout>(R.id.tabLayout)
        viewPager2.adapter = object : FragmentStateAdapter(this){  //适配器
            override fun getItemCount(): Int {    //告诉ViewPager2有几个页面
                return 3
            }

            override fun createFragment(position: Int): Fragment {   //创造Fragment的序号及内容
                return when(position){
                    0 -> ScaleFragment()
                    1 -> RotateFragment()
                    else -> TranslateFragment()
                }
            }
        }

        //将TabLayout和ViewPager2关联起来
        TabLayoutMediator(tabLayout,viewPager2){tab,position ->   //第三个参数为设置方法，这里直接用lambda表达式（如果最后一个参数用lambda表达式，则括号不用括起来） 根据position给tab设置标题
            when(position){
                0 -> tab.text = "缩放"
                1 -> tab.text = "旋转"
                else -> tab.text = "移动"
            }
        }.attach()
    }
}